<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description">
<meta property="og:type" content="website">
<meta property="og:title" content="Hexo">
<meta property="og:url" content="http://yoursite.com/page/11/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Hexo">
<meta name="twitter:description">
  
    <link rel="alternative" href="/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="/css/style.css" type="text/css">
  

</head>
<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" results="0" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main">
  
    <article id="post-log/6.logback系列之初始化" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/15/log/6.logback系列之初始化/" class="article-date">
  <time datetime="2015-12-14T22:00:00.000Z" itemprop="datePublished">2015-12-15</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/log/">log</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/15/log/6.logback系列之初始化/">logback系列二之初始化</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u521D_u59CB_u5316"><a href="#u521D_u59CB_u5316" class="headerlink" title="初始化"></a>初始化</h2><p>　　在StaticLoggerBinder的init方法中，我们可以看到一行关键的代码 <strong>new ContextInitializer(defaultLoggerContext).autoConfig();</strong>，进入autoConfig方法，其主要的作用就是获取配置文件logback.xml，并调用configureByResource进行解析工作，真正进行解析工作的则是由JoranConfigurator完成，此处对xml配置文件的解析细节不再做介绍</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/15/log/6.logback系列之初始化/" data-id="cijzzpvbt00aj1cfsrijz7epb" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/log/">log</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/logback/">logback</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-log/5.logback系列之入门" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/15/log/5.logback系列之入门/" class="article-date">
  <time datetime="2015-12-14T21:00:00.000Z" itemprop="datePublished">2015-12-15</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/log/">log</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/15/log/5.logback系列之入门/">logback系列一之入门</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　Logback是由log4j创始人设计的又一个开源日志组件。logback当前分成三个模块：logback-core、logback- classic和logback-access。logback-core是其它两个模块的基础模块。logback-classic是log4j的一个改良版本。此外logback-classic实现了SLF4J API，这样使你可以很方便地更换成其它日志系统如log4j或JDK14 Logging。logback-access访问模块与Servlet容器集成提供通过Http来访问日志的功能。<br>　　Logback作为新一代的日志框架，大有取代log4j的趋势。使用logback和log4j十分相似，log4j的属性配置文件可以通过工具<a href="http://logback.qos.ch/translator/" target="_blank" rel="external">http://logback.qos.ch/translator/</a>转换为logback的配置文件放到类路径里面去，另外再将logback的类库logback-core，logback-classic加入到类路径中去就搞定了。</p>
<h2 id="u73AF_u5883_u642D_u5EFA"><a href="#u73AF_u5883_u642D_u5EFA" class="headerlink" title="环境搭建"></a>环境搭建</h2><p>　　首先，我们引入在maven项目中引入jar包logback-classic，该包依赖的slf4j-api和logback-core，无需再引入。<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">groupId</span>&gt;</span>ch.qos.logback<span class="tag">&lt;/<span class="title">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">artifactId</span>&gt;</span>logback-classic<span class="tag">&lt;/<span class="title">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">version</span>&gt;</span>1.1.3<span class="tag">&lt;/<span class="title">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>　　这里仍然采用之前的测试类。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.slf4j.Logger;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Demo</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger log = LoggerFactory.getLogger(Demo.class);</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span>&#123;</span><br><span class="line">        System.out.println(log);</span><br><span class="line">        log.trace(<span class="string">"trace信息"</span>);</span><br><span class="line">        log.debug(<span class="string">"debug信息"</span>);</span><br><span class="line">        log.info(<span class="string">"info信息"</span>);</span><br><span class="line">        log.warn(<span class="string">"warn信息"</span>);</span><br><span class="line">        log.error(<span class="string">"error信息"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　最后新建logback.xml配置文件，如下：<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">configuration</span> <span class="attribute">scan</span>=<span class="value">"true"</span> <span class="attribute">scanPeriod</span>=<span class="value">"4 seconds"</span> <span class="attribute">debug</span>=<span class="value">"false"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">jmxConfigurator</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">contextName</span>&gt;</span>Authority-Manager<span class="tag">&lt;/<span class="title">contextName</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"LOG_HOME"</span> <span class="attribute">value</span>=<span class="value">"C:/logs/authority-manager/"</span> /&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 控制台输出日志 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">appender</span> <span class="attribute">name</span>=<span class="value">"STDOUT"</span> <span class="attribute">class</span>=<span class="value">"ch.qos.logback.core.ConsoleAppender"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">layout</span> <span class="attribute">class</span>=<span class="value">"ch.qos.logback.classic.PatternLayout"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">pattern</span>&gt;</span>%d&#123;yyyy-MM-dd HH:mm:ss&#125; [%thread] %-5level %logger&#123;36&#125; - %msg%n<span class="tag">&lt;/<span class="title">pattern</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="title">layout</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">appender</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 文件输出日志 (文件大小策略进行文件输出，超过指定大小对文件备份)--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">appender</span> <span class="attribute">name</span>=<span class="value">"FILE"</span> <span class="attribute">class</span>=<span class="value">"ch.qos.logback.core.rolling.RollingFileAppender"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">File</span>&gt;</span>$&#123;LOG_HOME&#125;/file.log<span class="tag">&lt;/<span class="title">File</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--当SizeBasedTriggeringPolicy触发时（即文件大小达到100MB），</span><br><span class="line">            则启动FixedWindowsRollingPolicy对日志文件进行滚动。</span><br><span class="line">            MinIndex和MaxIndex分别表示最小计数和最大计数。 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">rollingPolicy</span> <span class="attribute">class</span>=<span class="value">"ch.qos.logback.core.rolling.FixedWindowRollingPolicy"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">FileNamePattern</span>&gt;</span>file.log.%i.bak<span class="tag">&lt;/<span class="title">FileNamePattern</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">MinIndex</span>&gt;</span>1<span class="tag">&lt;/<span class="title">MinIndex</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">MaxIndex</span>&gt;</span>12<span class="tag">&lt;/<span class="title">MaxIndex</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="title">rollingPolicy</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">triggeringPolicy</span> <span class="attribute">class</span>=<span class="value">"ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">MaxFileSize</span>&gt;</span>10MB<span class="tag">&lt;/<span class="title">MaxFileSize</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="title">triggeringPolicy</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">layout</span> <span class="attribute">class</span>=<span class="value">"ch.qos.logback.classic.PatternLayout"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">Pattern</span>&gt;</span>%d&#123;yyyy-MM-dd HH:mm:ss&#125; [%thread] %-5level %logger&#123;36&#125; - %msg%n<span class="tag">&lt;/<span class="title">Pattern</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="title">layout</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">appender</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--每天生成一个日志文件，保存30天的日志文件。--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">appender</span> <span class="attribute">name</span>=<span class="value">"DayFile"</span> <span class="attribute">class</span>=<span class="value">"ch.qos.logback.core.rolling.RollingFileAppender"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">File</span>&gt;</span>$&#123;LOG_HOME&#125;/dayFile.log<span class="tag">&lt;/<span class="title">File</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">rollingPolicy</span> <span class="attribute">class</span>=<span class="value">"ch.qos.logback.core.rolling.TimeBasedRollingPolicy"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">fileNamePattern</span>&gt;</span>dayFile.%d&#123;yyyy-MM-dd&#125;.log<span class="tag">&lt;/<span class="title">fileNamePattern</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">maxHistory</span>&gt;</span>30<span class="tag">&lt;/<span class="title">maxHistory</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="title">rollingPolicy</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">encoder</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">pattern</span>&gt;</span>%-4relative [%thread] %-5level %logger&#123;35&#125; - %msg%n<span class="tag">&lt;/<span class="title">pattern</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="title">encoder</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">appender</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 日志输出级别 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">root</span> <span class="attribute">level</span>=<span class="value">" "</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">appender-ref</span> <span class="attribute">ref</span>=<span class="value">"STDOUT"</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">appender-ref</span> <span class="attribute">ref</span>=<span class="value">"FILE"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">root</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--权限拦截器日志打印--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">logger</span> <span class="attribute">name</span>=<span class="value">"com.shihc.logback.demo"</span> <span class="attribute">level</span>=<span class="value">"DEBUG"</span> <span class="attribute">additivity</span>=<span class="value">"false"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--同时向控制台和文件中输出--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">appender-ref</span> <span class="attribute">ref</span>=<span class="value">"STDOUT"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">appender-ref</span> <span class="attribute">ref</span>=<span class="value">"FILE"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">logger</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="title">logger</span> <span class="attribute">name</span>=<span class="value">"org.mybatis.spring"</span> <span class="attribute">level</span>=<span class="value">"INFO"</span> <span class="attribute">additivity</span>=<span class="value">"false"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--同时向控制台和文件中输出--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">appender-ref</span> <span class="attribute">ref</span>=<span class="value">"STDOUT"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">appender-ref</span> <span class="attribute">ref</span>=<span class="value">"FILE"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">logger</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="title">configuration</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>　　运行代码即可看到效果。如果对log4j的配置很熟悉的同学应该可以发现，这两者的配置都差不多，很多的概念几乎都一样，这里便不再对配置文件做过多的介绍。</p>
<h2 id="slf4j_u96C6_u6210"><a href="#slf4j_u96C6_u6210" class="headerlink" title="slf4j集成"></a>slf4j集成</h2><p>　　我们打开logback-classic的源码便可以发现，其存在两个主要的jar包，一个为ch.qos.logback.classic、另一个则与我们在slf4j-log4j12包中看到的一致，为org.slf4j.impl。在org.slf4j.impl包中，实现了类StaticLoggerBinder，正是之前文章提到的，如果第三方日志实现框架（这里指logback）与slf4j进行集成需要实现的类。</p>
<h2 id="Logback_u5305"><a href="#Logback_u5305" class="headerlink" title="Logback包"></a>Logback包</h2><p>　　Logback主要分为三个包：logback-core，logback-classic，logback-access<br>　　1. logback-core 是核心；<br>　　2. logback-classic 改善了log4j，且自身实现了SLF4J 必要接口，所以即使用Logback你仍然可以使用其他的日志实现，如原始的Log4J、java.util.logging等；<br>　　3. logback-access 让你方便的访问日志信息，如通过 http 的方式。</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/15/log/5.logback系列之入门/" data-id="cijzzpvbw00an1cfs4duqhp18" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/log/">log</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/logback/">logback</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-log/4.日志系列之log4j框架" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/15/log/4.日志系列之log4j框架/" class="article-date">
  <time datetime="2015-12-14T20:00:00.000Z" itemprop="datePublished">2015-12-15</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/log/">log</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/15/log/4.日志系列之log4j框架/">日志系列四之log4j框架</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="Appender"><a href="#Appender" class="headerlink" title="Appender"></a>Appender</h2><p>　　在log4j中，我们可以将日志输出到不同的地方，该功能的实现主要是由log4j提供的不同的Appender完成。下图所示红框内的为常用的几个，下面介绍另外几个重要的Appender。这里不再提供配置实例。<br>　　1. JDBCAppender：将日志写入数据库，里面的实现居然是短连接，每次插入数据时都要与数据库建立连接，然后断开连接，好鸡肋的功能！<br>　　2. SocketAppender：将日志通过Socket连接，发送到远程服务器上，注意，该SocketAppender无需配置layout，其是将LoggingEvent（包括了所有的日志信息）直接进行序列化，再通过网络发送。此时socket不会断开，连接一直保存。在log4j的源码中，作者也提供了服务端的实现，用来接收日志，详见包org.apache.log4j.net<br>　　3. SMTPAppender：发送日志给邮件<br><img src="/images/log4j-appender.jpg" alt="log4j-appender.jpg"></p>
<h2 id="Level"><a href="#Level" class="headerlink" title="Level"></a>Level</h2><p>　　level优先级分别为OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL7个级别。Log4j建议只使用四个级别，通过定义的级别，你可以控制程序中的日志输出。比如在这里定义了ERROR级别，程序中只有FARAL、ERROR 级别的LOG会被输出。</p>
<h2 id="Layout"><a href="#Layout" class="headerlink" title="Layout"></a>Layout</h2><p>　　log4j为日志的输出格式提供了如下几种模板：<br>　　1. HTMLLayout：以HTML表格形式布局<br>　　2. SimpleLayout：包含日志信息的级别和信息字符串<br>　　3. TTCCLayout：包含日志产生的时间、线程、类别等等信息<br>　　4. PatternLayout：可以灵活地指定布局模式</p>
<h2 id="additivity"><a href="#additivity" class="headerlink" title="additivity"></a>additivity</h2><p>　　子Logger 是否继承父 Logger 的 输出源（appender）的标志位。具体说，默认情况下子Logger会继承父Logger的appender，也就是说子Logger会在父Logger的appender里输出。若是additivity设为false，则子Logger只会在自己的appender里输出，而不会在父Logger的appender里输出。<br>　　在log4j中，基本上我们都会配置一个rootLogger，由于输出系统中所有的日志。但是，我们会遇到这样一个需求：将某个包下的日志单独输出到其他地方，无需再通过rootLogger的配置进行输出，那么此时该怎么办呢？这个时候additivity就派上用场了。如下所示，包com.mapbar.push.web.dao下的所有日志都单独输出到xxxxxx.log文件中<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">#此处配置可以打印出sql</span><br><span class="line">log4j.additivity.com.mapbar.push.web.dao=false</span><br><span class="line">log4j.logger.com.mapbar.push.web.dao=ERROR,SQLFILE</span><br><span class="line">log4j.appender.SQLFILE=org.apache.log4j.DailyRollingFileAppender</span><br><span class="line">log4j.appender.SQLFILE.File=xxxxxx.log</span><br><span class="line">log4j.appender.SQLFILE.Append=true</span><br><span class="line">log4j.appender.SQLFILE.Encoding=utf-8</span><br><span class="line">log4j.appender.SQLFILE.layout=org.apache.log4j.PatternLayout</span><br><span class="line">log4j.appender.SQLFILE.layout.ConversionPattern=[push-web] %d [%t] %-5p - %m%n</span><br></pre></td></tr></table></figure></p>
<h2 id="Hierarchy"><a href="#Hierarchy" class="headerlink" title="Hierarchy"></a>Hierarchy</h2><p>　　Hierarchy继承自LoggerRepository。顾名思义，它就是一个Logger实例的容器：一方面相同名字的Logger实例只需要创建一次，在后面的使用中，只需要从这个容器中取即可；另一方面，Logger容器可以存放从配置文件中解析出来的信息，从而使配置信息可以无缝的应用到Log4J内部系统中；最后Logger容器还为维护Logger的树状层次结构提供了方面，每个Logger只维护父节点的信息，有了Logger容器的存在则可以很容易的找到一个新的Logger实例的父节点；</p>
<h2 id="Filter"><a href="#Filter" class="headerlink" title="Filter"></a>Filter</h2><p>　　在Log4J中，Filter组成一条链，它定义了decide()方法，由子类实现，若返回DENY则日志不会被记录、NEUTRAL则继续检查下一个Filter实例、ACCEPT则Filter通过，继续执行后面的写日志操作。使用Filter可以为Appender加入一些除了threshold以外的其他逻辑，由于它本身是链状的，而且它的执行是横跨在Appender的doAppend方法中，因而这也是一个典型的AOP的概念。也类似于Servlet中的过滤器概念，只是在实现细节上存在细微的区别。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">Filter</span> <span class="keyword">implements</span> <span class="title">OptionHandler</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">public</span> Filter next;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span><br><span class="line">     The log event must be dropped immediately without consulting</span><br><span class="line">     with the remaining filters, if any, in the chain.  */</span></span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> DENY    = -<span class="number">1</span>;</span><br><span class="line">  </span><br><span class="line">  <span class="comment">/**</span><br><span class="line">     This filter is neutral with respect to the log event. The</span><br><span class="line">     remaining filters, if any, should be consulted for a final decision.</span><br><span class="line">  */</span></span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> NEUTRAL = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span><br><span class="line">     The log event must be logged immediately without consulting with</span><br><span class="line">     the remaining filters, if any, in the chain.  */</span></span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> ACCEPT  = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span><br><span class="line">     Usually filters options become active when set. We provide a</span><br><span class="line">     default do-nothing implementation for convenience.</span><br><span class="line">  */</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span></span><br><span class="line">  <span class="keyword">void</span> <span class="title">activateOptions</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**     </span><br><span class="line">     &lt;p&gt;If the decision is &lt;code&gt;DENY&lt;/code&gt;, then the event will be</span><br><span class="line">     dropped. If the decision is &lt;code&gt;NEUTRAL&lt;/code&gt;, then the next</span><br><span class="line">     filter, if any, will be invoked. If the decision is ACCEPT then</span><br><span class="line">     the event will be logged without consulting with other filters in</span><br><span class="line">     the chain.</span><br><span class="line"></span><br><span class="line">     <span class="doctag">@param</span> event The LoggingEvent to decide upon.</span><br><span class="line">     <span class="doctag">@return</span> decision The decision of the filter.  */</span></span><br><span class="line">  <span class="function"><span class="keyword">abstract</span></span><br><span class="line">  <span class="keyword">public</span></span><br><span class="line">  <span class="keyword">int</span> <span class="title">decide</span><span class="params">(LoggingEvent event)</span></span>;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNext</span><span class="params">(Filter next)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.next = next;</span><br><span class="line">  &#125;</span><br><span class="line"> </span><br><span class="line">  <span class="function"><span class="keyword">public</span> Filter <span class="title">getNext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> next;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="LoggingEvent"><a href="#LoggingEvent" class="headerlink" title="LoggingEvent"></a>LoggingEvent</h2><p>　　LoggingEvent个人感觉用LoggingContext更合适一些，它是对一次日志记录时哪能获取到的数据的封装。它包含了以下信息以提供Layout在format()方法中使用：</p>
<ol>
<li>fqnOfCategoryClass：日志记录接口（默认为Logger）的类全名，该信息主要用于计算日志记录点的源文件、调用方法以及行号等位置信息。</li>
<li>locationInfo：通过fqnOfCategoryClass计算位置信息，位置信息的计算由LocationInfo类实现，这些信息可以提供给Layout使用。</li>
<li>logger：目前来看主要是通过Logger实例取得LogRepository实例，并通过LogRepository取得注册的ObjectRender实例，如果有的话。</li>
<li>loggerName：当前日志记录的Logger名称，提供给Layout使用。</li>
<li>threadName：当前线程名，提供给Layout使用。</li>
<li>level：当前日志的级别，提供给Layout使用。</li>
<li>message：当前日志类，一般是String类型，但是也可以通过注册ObjectRender，然后传入相应的其他对象类型。</li>
<li>renderedMessage：经过ObjectRender处理后的日志信息，提供给Layout使用。</li>
<li>throwableInfo：异常信息，如果存在的话，提供给Layout使用。</li>
<li>timestamp：创建LoggingEvent实例的时间，提供给Layout使用。</li>
<li>其他相对不常用的信息将会在后面小节中讲解。<h2 id="ObjectRender"><a href="#ObjectRender" class="headerlink" title="ObjectRender"></a>ObjectRender</h2>　　Log4J中，对传入的message实例，如果是非String类型，会先使用注册的ObjectRender（在LogRepository中查找注册的ObjectRender信息）处理成String后返回，若没有找到相应的ObjectRender，则使用默认的ObjectRender，它只是调用该消息实例的toString()方法。</li>
</ol>
<h2 id="u914D_u7F6E_u793A_u4F8B"><a href="#u914D_u7F6E_u793A_u4F8B" class="headerlink" title="配置示例"></a>配置示例</h2><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"># 打开调试模式，输出log4j自身的日志信息</span><br><span class="line">log4j.debug=true</span><br><span class="line"># 设置最小阀值，此时系统输出的级别只会有INFO、WARN和ERROR等，防止其他Logger实例没有设置Level值的情况</span><br><span class="line">log4j.threshold=INFO</span><br><span class="line"># threshold设置为INFO，这里rootLogger设置为TRACE无效，最低级别仍然为INFO</span><br><span class="line">log4j.rootLogger=TRACE,CONSOLE,FILE</span><br><span class="line"></span><br><span class="line">log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender</span><br><span class="line">log4j.appender.CONSOLE.Encoding=utf-8</span><br><span class="line">log4j.appender.CONSOLE.Target=System.out </span><br><span class="line">log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout</span><br><span class="line">log4j.appender.CONSOLE.layout.ConversionPattern=[slf4j-demo] %d - %c -%-4r [%t] %-5p - %m%n</span><br><span class="line"></span><br><span class="line">log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender</span><br><span class="line">log4j.appender.FILE.File=demo.log</span><br><span class="line">log4j.appender.FILE.Append=true </span><br><span class="line">log4j.appender.FILE.Encoding=utf-8</span><br><span class="line">log4j.appender.FILE.layout=org.apache.log4j.PatternLayout </span><br><span class="line">log4j.appender.FILE.layout.ConversionPattern=[slf4j-demo] %d - %c -%-4r [%t] %-5p - %m%n</span><br></pre></td></tr></table></figure>
<p>下面附上一张调试模式下log4j自身的日志信息<br>log4j: Hierarchy threshold set to [INFO].<br>log4j: Parsing for [root] with value=[TRACE,CONSOLE,FILE].<br>log4j: Level token is [TRACE].<br>log4j: Category root set to TRACE<br>log4j: Parsing appender named “CONSOLE”.<br>log4j: Parsing layout options for “CONSOLE”.<br>log4j: Setting property [conversionPattern] to [[slf4j-demo] %d - %c -%-4r [%t] %-5p - %m%n].<br>log4j: End of parsing for “CONSOLE”.<br>log4j: Setting property [encoding] to [utf-8].<br>log4j: Setting property [target] to [System.out ].<br>log4j: Parsed “CONSOLE” options.<br>log4j: Parsing appender named “FILE”.<br>log4j: Parsing layout options for “FILE”.<br>log4j: Setting property [conversionPattern] to [[slf4j-demo] %d - %c -%-4r [%t] %-5p - %m%n].<br>log4j: End of parsing for “FILE”.<br>log4j: Setting property [append] to [true].<br>log4j: Setting property [encoding] to [utf-8].<br>log4j: Setting property [file] to [demo.log].<br>log4j: setFile called: demo.log, true<br>log4j: setFile ended<br>log4j: Appender [FILE] to be rolled at midnight.<br>log4j: Parsed “FILE” options.<br>log4j: Finished configuring.<br>org.slf4j.impl.Log4jLoggerAdapter(Demo)</p>
<h2 id="u53C2_u8003_u8D44_u6599"><a href="#u53C2_u8003_u8D44_u6599" class="headerlink" title="参考资料"></a>参考资料</h2><p><a href="http://www.blogjava.net/DLevin/archive/2012/06/28/381667.html" target="_blank" rel="external">http://www.blogjava.net/DLevin/archive/2012/06/28/381667.html</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/15/log/4.日志系列之log4j框架/" data-id="cijzzpvbz00ar1cfsok2q2736" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/log/">log</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/log4j/">log4j</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-log/3.日志系列之log4j初始化" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/15/log/3.日志系列之log4j初始化/" class="article-date">
  <time datetime="2015-12-14T19:00:00.000Z" itemprop="datePublished">2015-12-15</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/log/">log</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/15/log/3.日志系列之log4j初始化/">日志系列三之log4j初始化</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　Log4j是Apache的一个开放源代码项目，通过使用Log4j，我们可以控制日志信息输出地，也可以控制每一条日志的输出格式。通过定义每一条日志信息的级别，我们能够更加细致地控制日志的生成过程。最令人感兴趣的就是，这些可以通过一个配置文件来灵活地进行配置，而不需要修改应用的代码。首先我们在代码中增加配置文件</p>
<h2 id="u5DE5_u4F5C_u539F_u7406"><a href="#u5DE5_u4F5C_u539F_u7406" class="headerlink" title="工作原理"></a>工作原理</h2><p>　　这里我们就不再搭建示例工程了，直接根据上一篇的示例代码，深入log4j的内部，了解配置文件初始化的过程。当我们调用slf4j的LoggerFactory.getLogger(…)方法时，会执行到在slf4j-log4j12桥接包中org.slf4j.impl.Log4jLoggerFactory类的getLogger方法，该方法实现如下。最终程序会执行到此处log4jLogger = LogManager.getLogger(name)。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">  <span class="function"><span class="keyword">public</span> Logger <span class="title">getLogger</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">    Logger slf4jLogger = loggerMap.get(name);</span><br><span class="line">    <span class="keyword">if</span> (slf4jLogger != <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> slf4jLogger;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      org.apache.log4j.Logger log4jLogger;</span><br><span class="line">      <span class="keyword">if</span>(name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME))</span><br><span class="line">        log4jLogger = LogManager.getRootLogger();</span><br><span class="line">      <span class="keyword">else</span></span><br><span class="line">        log4jLogger = LogManager.getLogger(name);</span><br><span class="line"></span><br><span class="line">      Logger newInstance = <span class="keyword">new</span> Log4jLoggerAdapter(log4jLogger);</span><br><span class="line">      Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);</span><br><span class="line">      <span class="keyword">return</span> oldInstance == <span class="keyword">null</span> ? newInstance : oldInstance;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　我们进入LogManager源码，可以看到其包含了一个static代码块，下面所示为关键的几行代码，显示了配置文件的加载流程<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">public</span> <span class="keyword">final</span> String DEFAULT_CONFIGURATION_FILE = <span class="string">"log4j.properties"</span>;</span><br><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> String DEFAULT_XML_CONFIGURATION_FILE = <span class="string">"log4j.xml"</span>;  </span><br><span class="line"><span class="keyword">static</span> &#123;</span><br><span class="line">    String configurationOptionStr = OptionConverter.getSystemProperty(DEFAULT_CONFIGURATION_KEY, <span class="keyword">null</span>);</span><br><span class="line">    String configuratorClassName = OptionConverter.getSystemProperty(CONFIGURATOR_CLASS_KEY, <span class="keyword">null</span>);</span><br><span class="line"></span><br><span class="line">    URL url = <span class="keyword">null</span>;</span><br><span class="line">    <span class="comment">//优先加载log4j.xml</span></span><br><span class="line">    url = Loader.getResource(DEFAULT_XML_CONFIGURATION_FILE);</span><br><span class="line">    <span class="keyword">if</span>(url == <span class="keyword">null</span>) &#123;</span><br><span class="line"><span class="comment">//如果没有log4j.xml，再加载log4j.properties</span></span><br><span class="line">   url = Loader.getResource(DEFAULT_CONFIGURATION_FILE);</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="keyword">if</span>(url != <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">          OptionConverter.selectAndConfigure(url, configuratorClassName, LogManager.getLoggerRepository());</span><br><span class="line">      &#125; <span class="keyword">catch</span> (NoClassDefFoundError e) &#123;</span><br><span class="line">          LogLog.warn(<span class="string">"Error during default initialization"</span>, e);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">   LogLog.debug(<span class="string">"Could not find resource: ["</span>+configurationOptionStr+<span class="string">"]."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　我们可以发现，在log4j的配置文件加载后，会调用OptionConverter.selectAndConfigure开始对log.properties内容进行解析。在selectAndConfigure中会调用PropertyConfigurator.doConfigure(url, loggerRepository)进行具体的内容解析工作。下面我们列出重载的方法doConfigure的源码，请注意代码中的注释部分<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doConfigure</span><span class="params">(Properties properties, LoggerRepository hierarchy)</span> </span>&#123;</span><br><span class="line">repository = hierarchy;</span><br><span class="line"><span class="comment">//DEBUG_KEY = log4j.debug，所以可以在log4j.properties中配置log4j.debug=true，打印内部的初始化过程日志信息</span></span><br><span class="line">   String value = properties.getProperty(LogLog.DEBUG_KEY);</span><br><span class="line">   <span class="keyword">if</span>(value == <span class="keyword">null</span>) &#123;</span><br><span class="line">     value = properties.getProperty(<span class="string">"log4j.configDebug"</span>);</span><br><span class="line">     <span class="keyword">if</span>(value != <span class="keyword">null</span>)</span><br><span class="line">LogLog.warn(<span class="string">"[log4j.configDebug] is deprecated. Use [log4j.debug] instead."</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span>(value != <span class="keyword">null</span>) &#123;</span><br><span class="line">     <span class="comment">//此处设置，用于打印log4j内部的配置文件解析日志</span></span><br><span class="line">     LogLog.setInternalDebugging(OptionConverter.toBoolean(value, <span class="keyword">true</span>));</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//   if log4j.reset=true then reset hierarchy</span></span><br><span class="line">   String reset = properties.getProperty(RESET_KEY);</span><br><span class="line">   <span class="keyword">if</span> (reset != <span class="keyword">null</span> &amp;&amp; OptionConverter.toBoolean(reset, <span class="keyword">false</span>)) &#123;</span><br><span class="line">         hierarchy.resetConfiguration();</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="comment">//THRESHOLD_PREFIX = log4j.threshold</span></span><br><span class="line">   String thresholdStr = OptionConverter.findAndSubst(THRESHOLD_PREFIX, properties);</span><br><span class="line">   <span class="keyword">if</span>(thresholdStr != <span class="keyword">null</span>) &#123;</span><br><span class="line">     hierarchy.setThreshold(OptionConverter.toLevel(thresholdStr, (Level) Level.ALL));</span><br><span class="line">     LogLog.debug(<span class="string">"Hierarchy threshold set to ["</span>+hierarchy.getThreshold()+<span class="string">"]."</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="comment">//初始化log4j.rootLogger</span></span><br><span class="line">   configureRootCategory(properties, hierarchy);</span><br><span class="line"><span class="comment">//初始化LoggerFactory</span></span><br><span class="line">   configureLoggerFactory(properties);</span><br><span class="line"><span class="comment">//初始化log4j.logger等</span></span><br><span class="line">   parseCatsAndRenderers(properties, hierarchy);</span><br><span class="line"></span><br><span class="line">   LogLog.debug(<span class="string">"Finished configuring."</span>);</span><br><span class="line">   <span class="comment">// We don't want to hold references to appenders preventing their</span></span><br><span class="line">   <span class="comment">// garbage collection.</span></span><br><span class="line">   registry.clear();</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure></p>
<p>　　下面直接提出powserdesign画的oom图，便于理解<br><img src="/images/log4j-oom.jpg" alt="log4j-oom.jpg"></p>
<h2 id="u603B_u7ED3"><a href="#u603B_u7ED3" class="headerlink" title="总结"></a>总结</h2><p>　　1. 以DEBUG等级创建一个RootLogger,然后以RootLogger为参数创建一个Hierarchy类的实例。<br>　　2. Hierarchy类中实现了LoggerRepository接口和RendererSupport接口。LoggerRepository接口主要提供了对Logger聚集的一些访问方法和整个<br>Log容器对Threshold等级的支持。Hierarchy类其实是Log4j中最重要的一个容器类，其中保存了所有的logger实例，并提供相应的方法维护Logger的登记结构。<br>　　3. 以Hierarchy为参数创建一个DefaultRepositorySelector类的实例。以便提供一种获取LoggerRepository的方法。<br>　　4. DefaultRepositorySelector类实现了RepositorySelector接口。RepositorySelector提供了一个获取LoggerRepository的方法。<br>　　5. 之后开始读取默认配置文件。首先尝试读取Log4j.xml，如果不存在就读取Log4j.properties。如果都不存在就放弃作默认配置。继续运行。如果自己在程序中没有配置Log4j，以后的运行打印出错Log。</p>
<h2 id="u53C2_u8003_u8D44_u6599"><a href="#u53C2_u8003_u8D44_u6599" class="headerlink" title="参考资料"></a>参考资料</h2><p><a href="http://www.blogjava.net/DLevin/archive/2012/11/08/390991.html" target="_blank" rel="external">http://www.blogjava.net/DLevin/archive/2012/11/08/390991.html</a><br><a href="http://blog.csdn.net/shrekmu/article/details/271770" target="_blank" rel="external">http://blog.csdn.net/shrekmu/article/details/271770</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/15/log/3.日志系列之log4j初始化/" data-id="cijzzpvc300aw1cfs1o2s4m04" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/log/">log</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/log4j/">log4j</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-log/2.日志系列之slf4j" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/15/log/2.日志系列之slf4j/" class="article-date">
  <time datetime="2015-12-14T18:00:00.000Z" itemprop="datePublished">2015-12-15</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/log/">log</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/15/log/2.日志系列之slf4j/">日志系列二之slf4j</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　slf4j（org.slf4j:slf4j-api:1.7.7）与上一篇介绍的commons-logging组件类似，作为日志系统的基石，提供了接口规范，但是缺少默认的实现。基于该接口规范之上的日志实现包有：slf4j-nop.jar、slf4j-simple.jar、slf4j-log4j12.jar、slf4j-jdk14.jar和logback-classic.jar等。所以在加入slf4j-api-xx.jar包之后，需要再导入以上几个包中的任意一个包。废话不多说，先建立一个示例工程。</p>
<h2 id="u4F7F_u7528_u793A_u4F8B"><a href="#u4F7F_u7528_u793A_u4F8B" class="headerlink" title="使用示例"></a>使用示例</h2><p>　　首先在pom.xml中引入jar包<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">groupId</span>&gt;</span>org.slf4j<span class="tag">&lt;/<span class="title">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">artifactId</span>&gt;</span>slf4j-api<span class="tag">&lt;/<span class="title">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">version</span>&gt;</span>1.7.7<span class="tag">&lt;/<span class="title">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>　　再直接添加测试类<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Demo</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger log = LoggerFactory.getLogger(Demo.class);</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span>&#123;</span><br><span class="line">        System.out.println(log);</span><br><span class="line">        log.trace(<span class="string">"trace信息"</span>);</span><br><span class="line">        log.debug(<span class="string">"debug信息"</span>);</span><br><span class="line">        log.info(<span class="string">"info信息"</span>);</span><br><span class="line">        log.warn(<span class="string">"warn信息"</span>);</span><br><span class="line">        log.error(<span class="string">"error信息"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　运行后，打印信息如下。<br>SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.<br>SLF4J: Defaulting to no-operation (NOP) logger implementation<br>SLF4J: See <a href="http://www.slf4j.org/codes.html#StaticLoggerBinder" target="_blank" rel="external">http://www.slf4j.org/codes.html#StaticLoggerBinder</a> for further details.<br>org.slf4j.helpers.NOPLogger(NOP)<br>　　运行失败，提示未找到org.slf4j.impl.StaticLoggerBinder，这也印证了上文所说的，slf4j只是提供了接口规范，需要与对应的实现包配合使用。下面我们增加包slf4j-simple<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">groupId</span>&gt;</span>org.slf4j<span class="tag">&lt;/<span class="title">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">artifactId</span>&gt;</span>slf4j-simple<span class="tag">&lt;/<span class="title">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">version</span>&gt;</span>1.7.7<span class="tag">&lt;/<span class="title">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>　　再次执行，输出如下<br>org.slf4j.impl.SimpleLogger(Demo)<br>[main] INFO Demo - info信息<br>[main] WARN Demo - warn信息<br>[main] ERROR Demo - error信息</p>
<p>　　如果我们将slf4j-simple替换成slf4j-nop，则只输出了org.slf4j.helpers.NOPLogger(NOP)，没打印其他的日志信息。这是为什么呢？进入org.slf4j.helpers.NOPLogger源码，可以看到其info、warn、error等方法体都是空的，没有任何打印输出。</p>
<p>　　如果我们同时添加了实现slf4j-simple和slf4j-nop，则会打印如下信息<br>SLF4J: Class path contains multiple SLF4J bindings.<br>SLF4J: Found binding in [jar:file:/D:/Program%20Files/apache-maven-3.3.3/repo/org/slf4j/slf4j-simple/1.7.7/slf4j-simple-1.7.7.jar!/org/slf4j/impl/StaticLoggerBinder.class]<br>SLF4J: Found binding in [jar:file:/D:/Program%20Files/apache-maven-3.3.3/repo/org/slf4j/slf4j-nop/1.7.7/slf4j-nop-1.7.7.jar!/org/slf4j/impl/StaticLoggerBinder.class]<br>SLF4J: See <a href="http://www.slf4j.org/codes.html#multiple_bindings" target="_blank" rel="external">http://www.slf4j.org/codes.html#multiple_bindings</a> for an explanation.<br>SLF4J: Actual binding is of type [org.slf4j.impl.SimpleLoggerFactory]<br>[main] INFO Demo - info信息<br>[main] WARN Demo - warn信息<br>[main] ERROR Demo - error信息<br>org.slf4j.impl.SimpleLogger(Demo)</p>
<p>　　在日志中提示，找到了两个StaticLoggerBinder实现，程序采用的是org.slf4j.impl.SimpleLoggerFactory]<br>[main] INFO Demo - info信息的实现。下面我将代理大家分析该现象。<br>　　这里我们直接列出方法的调用链：LoggerFactory.getLogger -&gt; LoggerFactory.getILoggerFactory -&gt; LoggerFactory.bind -&gt; LoggerFactory.findPossibleStaticLoggerBinderPathSet，findPossibleStaticLoggerBinderPathSet方法实现如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> Set&lt;URL&gt; <span class="title">findPossibleStaticLoggerBinderPathSet</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="comment">// use Set instead of list in order to deal with  bug #138</span></span><br><span class="line">  <span class="comment">// LinkedHashSet appropriate here because it preserves insertion order during iteration</span></span><br><span class="line">  Set&lt;URL&gt; staticLoggerBinderPathSet = <span class="keyword">new</span> LinkedHashSet&lt;URL&gt;();</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    ClassLoader loggerFactoryClassLoader = LoggerFactory.class</span><br><span class="line">            .getClassLoader();</span><br><span class="line">    Enumeration&lt;URL&gt; paths;</span><br><span class="line">    <span class="comment">//STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class";</span></span><br><span class="line">    <span class="keyword">if</span> (loggerFactoryClassLoader == <span class="keyword">null</span>) &#123;</span><br><span class="line">      paths = ClassLoader.getSystemResources(STATIC_LOGGER_BINDER_PATH);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      paths = loggerFactoryClassLoader</span><br><span class="line">              .getResources(STATIC_LOGGER_BINDER_PATH);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">while</span> (paths.hasMoreElements()) &#123;</span><br><span class="line">      URL path = (URL) paths.nextElement();</span><br><span class="line">      staticLoggerBinderPathSet.add(path);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125; <span class="keyword">catch</span> (IOException ioe) &#123;</span><br><span class="line">    Util.report(<span class="string">"Error getting resources from path"</span>, ioe);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> staticLoggerBinderPathSet;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　findPossibleStaticLoggerBinderPathSet方法实现了找到classpath下所有的StaticLoggerBinder，如果找到了多个，则打印之前的警告信息。jvm貌似会选取第一个实现进行使用（根据上面的日志信息，先找到了slf4j-simple，并且打印了信息）</p>
<h2 id="u52A0_u8F7D_u6D41_u7A0B"><a href="#u52A0_u8F7D_u6D41_u7A0B" class="headerlink" title="加载流程"></a>加载流程</h2><p>　　我们在调用LoggerFactory.getLogger方法的时候，最终会调用如下代码。可以看到，是通过ILoggerFactory获取的Logger，而getILoggerFactory方法中的StaticLoggerBinder则为slf4j-simple包中的实现。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Logger <span class="title">getLogger</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">    ILoggerFactory iLoggerFactory = getILoggerFactory();</span><br><span class="line">    <span class="keyword">return</span> iLoggerFactory.getLogger(name);</span><br><span class="line">  &#125;</span><br><span class="line">　　　　</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ILoggerFactory <span class="title">getILoggerFactory</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (INITIALIZATION_STATE == UNINITIALIZED) &#123;</span><br><span class="line">      INITIALIZATION_STATE = ONGOING_INITIALIZATION;</span><br><span class="line">      performInitialization();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">switch</span> (INITIALIZATION_STATE) &#123;</span><br><span class="line">      <span class="keyword">case</span> SUCCESSFUL_INITIALIZATION:</span><br><span class="line">        <span class="comment">//测试程序会进入该分支执行</span></span><br><span class="line">        <span class="keyword">return</span> StaticLoggerBinder.getSingleton().getLoggerFactory();</span><br><span class="line">      <span class="keyword">case</span> NOP_FALLBACK_INITIALIZATION:</span><br><span class="line">        <span class="keyword">return</span> NOP_FALLBACK_FACTORY;</span><br><span class="line">      <span class="keyword">case</span> FAILED_INITIALIZATION:</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(UNSUCCESSFUL_INIT_MSG);</span><br><span class="line">      <span class="keyword">case</span> ONGOING_INITIALIZATION:</span><br><span class="line">        <span class="comment">// support re-entrant behavior.</span></span><br><span class="line">        <span class="comment">// See also http://bugzilla.slf4j.org/show_bug.cgi?id=106</span></span><br><span class="line">        <span class="keyword">return</span> TEMP_FACTORY;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">"Unreachable code"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　StaticLoggerBinder类继承自slf4j-api包中的LoggerFactoryBinder接口。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">LoggerFactoryBinder</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> ILoggerFactory <span class="title">getLoggerFactory</span><span class="params">()</span></span>;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> String <span class="title">getLoggerFactoryClassStr</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　这里我们只关心他的getLoggerFactory方法，我们分别进入slf4j-simple和slf4j-nop中的StaticLoggerBinder实现。可以看到getLoggerFactory分别返回了SimpleLoggerFactory和NOPLoggerFactory。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//slf4j-nop</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StaticLoggerBinder</span>  <span class="keyword">implements</span> <span class="title">LoggerFactoryBinder</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> StaticLoggerBinder SINGLETON = <span class="keyword">new</span> StaticLoggerBinder();</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> StaticLoggerBinder <span class="title">getSingleton</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> SINGLETON;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">static</span> String REQUESTED_API_VERSION = <span class="string">"1.6.99"</span>;  <span class="comment">// !final</span></span><br><span class="line">  </span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String loggerFactoryClassStr = NOPLoggerFactory.class.getName();</span><br><span class="line"></span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">final</span> ILoggerFactory loggerFactory;</span><br><span class="line">  </span><br><span class="line">  <span class="function"><span class="keyword">private</span> <span class="title">StaticLoggerBinder</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    loggerFactory = <span class="keyword">new</span> NOPLoggerFactory();</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  <span class="function"><span class="keyword">public</span> ILoggerFactory <span class="title">getLoggerFactory</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> loggerFactory;</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  <span class="function"><span class="keyword">public</span> String <span class="title">getLoggerFactoryClassStr</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> loggerFactoryClassStr;</span><br><span class="line">  &#125;   </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//slf4j-simple</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StaticLoggerBinder</span> <span class="keyword">implements</span> <span class="title">LoggerFactoryBinder</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> StaticLoggerBinder SINGLETON = <span class="keyword">new</span> StaticLoggerBinder();</span><br><span class="line">  </span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> StaticLoggerBinder <span class="title">getSingleton</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> SINGLETON;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">static</span> String REQUESTED_API_VERSION = <span class="string">"1.6.99"</span>;  <span class="comment">// !final</span></span><br><span class="line">  </span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String loggerFactoryClassStr = SimpleLoggerFactory.class.getName();</span><br><span class="line"></span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">final</span> ILoggerFactory loggerFactory;</span><br><span class="line">  </span><br><span class="line">  <span class="function"><span class="keyword">private</span> <span class="title">StaticLoggerBinder</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    loggerFactory = <span class="keyword">new</span> SimpleLoggerFactory();</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  <span class="function"><span class="keyword">public</span> ILoggerFactory <span class="title">getLoggerFactory</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> loggerFactory;</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  <span class="function"><span class="keyword">public</span> String <span class="title">getLoggerFactoryClassStr</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> loggerFactoryClassStr;</span><br><span class="line">  &#125;   </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="u6269_u5C55"><a href="#u6269_u5C55" class="headerlink" title="扩展"></a>扩展</h2><p>　　通过上面的分析，可以看到，不同于Commons Logging的动态绑定机制，SLF4J采用了一种静态绑定的机制。如果新的日志框架需要支持slf4j，则只需要以下几步<br>　　1. 实现Logger接口的类<br>　　2. 实现ILoggerFactory接口的类<br>　　3. 实现LoggerFactoryBinder接口的类StaticLoggerBinder（必须使用StaticLoggerBinder类名），并且存在一个静态的getSingleton()方法。<br>　　4. 实现MarkerFactoryBinder类的StaticMarkerBinder类（必须使用StaticMarkerBinder类名），可选。一般也会存在一个静态的SINGLETON字段，不过也是可选的。<br>　　5. 实现StaticMDCBinder类，可选。一般也会存在一个静态的SINGLETON字段，也可选。<br>　　下面我们以log4j为例，看看他是如何实现与slf4j的桥接的！</p>
<h2 id="u63A5_u5165log4j"><a href="#u63A5_u5165log4j" class="headerlink" title="接入log4j"></a>接入log4j</h2><p>　　在pom.xml中只需要引入包slf4j-log4j12，其他的删除，该包依赖log4j和slf4j-api两个包，故不需再导入<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">dependency</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="title">groupId</span>&gt;</span>org.slf4j<span class="tag">&lt;/<span class="title">groupId</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="title">artifactId</span>&gt;</span>slf4j-log4j12<span class="tag">&lt;/<span class="title">artifactId</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="title">version</span>&gt;</span>1.7.7<span class="tag">&lt;/<span class="title">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>　　此时运行代码，输出如下，提示找不到log4j的配置文件<br>org.slf4j.impl.Log4jLoggerAdapter(Demo)<br>log4j:WARN No appenders could be found for logger (Demo).<br>log4j:WARN Please initialize the log4j system properly.<br>log4j:WARN See <a href="http://logging.apache.org/log4j/1.2/faq.html#noconfig" target="_blank" rel="external">http://logging.apache.org/log4j/1.2/faq.html#noconfig</a> for more info.</p>
<p>　　包slf4j-log4j12是如何实现slf4j和log4j的桥接工作的呢。我们再次进入slf4j-log4j12源码，可以看到其实现了StaticLoggerBinder（继承自LoggerFactoryBinder）和Log4jLoggerFactory（继承自ILoggerFactory）。与上面所示的扩展方法一致。</p>
<h2 id="u603B_u7ED3"><a href="#u603B_u7ED3" class="headerlink" title="总结"></a>总结</h2><p>　　通过上面分析，可以看到，SLF4J在classpath下只支持一个桥接包（slf4j-simple-<version>.jar、slf4j-log4j12-<version>.jar、slf4j-jdk14-<version>.jar、logback-classic-<version>.jar等）。如果在classpath下存在多个桥接包，具体用哪个就要看这几个桥接包的加载顺序了，实际中会使用先加载的桥接包。同时SLF4J会打印使用哪个桥接包，哪些桥接包没有使用。源码详见：<a href="/code/slf4j-demo.zip">slf4j-demo.rar</a></version></version></version></version></p>
<h2 id="u53C2_u8003_u8D44_u6599"><a href="#u53C2_u8003_u8D44_u6599" class="headerlink" title="参考资料"></a>参考资料</h2><p><a href="http://www.blogjava.net/DLevin/archive/2012/11/08/390991.html" target="_blank" rel="external">http://www.blogjava.net/DLevin/archive/2012/11/08/390991.html</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/15/log/2.日志系列之slf4j/" data-id="cijzzpvc600b01cfsc2negxht" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/log/">log</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/slf4j/">slf4j</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-log/1.日志系列之commons-logging" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/15/log/1.日志系列之commons-logging/" class="article-date">
  <time datetime="2015-12-14T17:00:01.000Z" itemprop="datePublished">2015-12-15</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/log/">log</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/15/log/1.日志系列之commons-logging/">日志系列一之commons-logging</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　做过java服务端开发的程序员都会遇到日志记录的问题，目前，各个框架采用的日志组件都不一样，比如spring core、spring jdbc等核心组件采用的就是commons-logging日志框架。而可以与spring集成的周边产品，如mybatis、dubbo等则通过提供配置选项实现不同日志框架的接入。同时，spring自家的产品spring boot默认采用的日志框架则为logback，当然，也支持log4j等其他的日志框架。<br>　　那么问题来了，当这些组件都被某一个服务同时使用的时候，他们是如何协同工作的呢？下面我将通过一系列文章，带领大家一一探究不同日志框架的原理性问题。本篇文章将主要介绍commons-logging的使用方法和实现机制</p>
<h2 id="u4F7F_u7528_u793A_u4F8B"><a href="#u4F7F_u7528_u793A_u4F8B" class="headerlink" title="使用示例"></a>使用示例</h2><p>　　首先在pom.xml中引入jar包<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">groupId</span>&gt;</span>commons-logging<span class="tag">&lt;/<span class="title">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">artifactId</span>&gt;</span>commons-logging<span class="tag">&lt;/<span class="title">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">version</span>&gt;</span>1.2<span class="tag">&lt;/<span class="title">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>　　先直接添加测试类<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Demo</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Log log = LogFactory.getLog(Demo.class);</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span>&#123;</span><br><span class="line">        System.out.println(log);</span><br><span class="line">        log.trace(<span class="string">"trace信息"</span>);</span><br><span class="line">        log.debug(<span class="string">"debug信息"</span>);</span><br><span class="line">        log.info(<span class="string">"info信息"</span>);</span><br><span class="line">        log.warn(<span class="string">"warn信息"</span>);</span><br><span class="line">        log.error(<span class="string">"error信息"</span>);</span><br><span class="line">        log.fatal(<span class="string">"fatal信息"</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　运行后，打印信息如下。注意，此时没有添加commons-logging的配置文件<br>org.apache.commons.logging.impl.Jdk14Logger@6688cf9e<br>十二月 15, 2015 10:55:21 上午 Demo main<br>INFO: info信息<br>十二月 15, 2015 10:55:21 上午 Demo main<br>WARNING: warn信息<br>十二月 15, 2015 10:55:21 上午 Demo main<br>SEVERE: error信息<br>十二月 15, 2015 10:55:21 上午 Demo main<br>SEVERE: fatal信息</p>
<p>　　通过日志信息，我们可以看出，此时Log实例为org.apache.commons.logging.impl.Jdk14Logger，并没有输出trace和debug级别的信息。<br>　　关于为什么没出输出trace和debug的问题，与jdk提供的日志组件有关，jdk的日志组件默认的级别为INFO，即使在代码中调用((Jdk14Logger) log).getLogger().setLevel(java.util.logging.Level.FINEST);，也没有效果。但如果设置为：Level.WARNING，则产生效果，输出warn、error和fatal信息。进入源码可以发现，log.trace(“trace信息”)方法调用了Jdk14Logger.log(Level.FINEST, String.valueOf(message), null)方法。<br>　　commons-logging采用Jdk14Logger的机制原理，我将进入源码为大家解答。</p>
<h2 id="LOG_u63A5_u53E3"><a href="#LOG_u63A5_u53E3" class="headerlink" title="LOG接口"></a>LOG接口</h2><p>　　在commons-logging中，org.apache.commons.logging.Log作为一个接口，有如下图红框内所示的几个实现。在测试示例中为什么会选择org.apache.commons.logging.impl.Jdk14Logger呢！下面我们进入LogFactory.getLog方法一探究竟！<br><img src="/images/commons-logging-log接口.jpg" alt="commons-logging-log接口.jpg"><br>　　程序在调用LogFactory.getLog方法后，最终会执行到方法getInstance方法，如下所示<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Log <span class="title">getInstance</span><span class="params">(String name)</span> <span class="keyword">throws</span> LogConfigurationException </span>&#123;</span><br><span class="line">    Log instance = (Log) instances.get(name);</span><br><span class="line">    <span class="keyword">if</span> (instance == <span class="keyword">null</span>) &#123;</span><br><span class="line">        instance = newInstance(name);</span><br><span class="line">        instances.put(name, instance);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> instance;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　在上面的方法中，最重要的则为newInstance方法，该方法内调用了discoverLogImplementation方法，下面我直接进入discoverLogImplementation方法，其关键代码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>; i&lt;classesToDiscover.length &amp;&amp; result == <span class="keyword">null</span>; ++i) &#123;</span><br><span class="line">    result = createLogFromClass(classesToDiscover[i], logCategory, <span class="keyword">true</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>而数组classesToDiscover的定义如下；<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String[] classesToDiscover = &#123;</span><br><span class="line">        LOGGING_IMPL_LOG4J_LOGGER,　<span class="comment">/*LOGGING_IMPL_LOG4J_LOGGER = org.apache.commons.logging.impl.Log4JLogger;*/</span></span><br><span class="line">        <span class="string">"org.apache.commons.logging.impl.Jdk14Logger"</span>,</span><br><span class="line">        <span class="string">"org.apache.commons.logging.impl.Jdk13LumberjackLogger"</span>,</span><br><span class="line">        <span class="string">"org.apache.commons.logging.impl.SimpleLog"</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>　　可以看到，Log接口优先使用Log4JLogger实现，接着是Jdk14Logger、Jdk13LumberjackLogger，最后为SimpleLog。在Log4JLogger中存在一个静态代码块，如下所示，其中类Priority、Level等均为log4j包中的类，由于未引入log4j的包，导致首次循环调用createLogFromClass方法时，初始化失败，返回null。进入下一次循环，采用Jdk14Logger的实现。初始化成功，所以测试程序中打印的为org.apache.commons.logging.impl.Jdk14Logger@1310c2e8<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (!Priority.class.isAssignableFrom(Level.class)) &#123;</span><br><span class="line">        <span class="comment">// nope, this is log4j 1.3, so force an ExceptionInInitializerError</span></span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> InstantiationError(<span class="string">"Log4J 1.2 not available"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Priority _traceLevel;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        _traceLevel = (Priority) Level.class.getDeclaredField(<span class="string">"TRACE"</span>).get(<span class="keyword">null</span>);</span><br><span class="line">    &#125; <span class="keyword">catch</span>(Exception ex) &#123;</span><br><span class="line">        <span class="comment">// ok, trace not available</span></span><br><span class="line">        _traceLevel = Level.DEBUG;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//默认为trace级别</span></span><br><span class="line">    traceLevel = _traceLevel;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　从上面的分析可以看出，commons-logging默认采用的日志实现框架，优先级依次为：Log4JLogger、Jdk14Logger、Jdk13LumberjackLogger和SimpleLog。</p>
<h2 id="u63A5_u5165log4j"><a href="#u63A5_u5165log4j" class="headerlink" title="接入log4j"></a>接入log4j</h2><p>　　首先我们引入log4j包，如下。<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">groupId</span>&gt;</span>log4j<span class="tag">&lt;/<span class="title">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">artifactId</span>&gt;</span>log4j<span class="tag">&lt;/<span class="title">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">version</span>&gt;</span>1.2.17<span class="tag">&lt;/<span class="title">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>　　运行程序，结果如下，可以看到，此时<strong>提示没有找到log4j的配置文件</strong>，故没有输出任何日志信息，后面几篇文章我们再介绍log4j<br>org.apache.commons.logging.impl.Log4JLogger@49c1e1e7<br>log4j:WARN No appenders could be found for logger (Demo).<br>log4j:WARN Please initialize the log4j system properly.<br>log4j:WARN See <a href="http://logging.apache.org/log4j/1.2/faq.html#noconfig" target="_blank" rel="external">http://logging.apache.org/log4j/1.2/faq.html#noconfig</a> for more info.</p>
<h2 id="u4F7F_u7528SimpleLog"><a href="#u4F7F_u7528SimpleLog" class="headerlink" title="使用SimpleLog"></a>使用SimpleLog</h2><p>　　simpleLog为commons-logging中实现的一个向控制台数据的类。先增加配置文件commons-logging.properties，并增加内容：org.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog，此时测试输出结果如下：<br>　　org.apache.commons.logging.impl.SimpleLog@39242445<br>　　[INFO] Demo - info信息<br>　　[WARN] Demo - warn信息<br>　　[ERROR] Demo - error信息<br>　　[FATAL] Demo - </p>
<p>　　可以看到，当我们在配置文件中指定了Log类型后，则会覆盖默认的优先使用顺序：Log4JLogger、Jdk14Logger、Jdk13LumberjackLogger、SimpleLog。直接采用配置文件中指定的Log类型。</p>
<h2 id="LogFactory"><a href="#LogFactory" class="headerlink" title="LogFactory"></a>LogFactory</h2><p>　　上面的示例都是通过LogFactory获取的。那么，LogFactory有哪些功能呢？首先，LogFactory是一个抽象类，在初始化的时候，其会在getFactory()方法中寻找具体的实现类，下面直接列出结果：<br>　　1. 根据类加载器，找到通过该加载器加载的LogFactory实例（通过key-value的形式存放在Hashtable中），找到则直接返回，否则进入第下步<br>　　2. 从System Property中查找LogFactory，如果没找到，则进入下一步，否则直接到最后一步。<br>　　3. 从文件META-INF/services/org.apache.commons.logging.LogFactory中查找（类似于java SPI机制，），如果没找到，则进入下一步，找到则直接到最后一步。<br>　　4. 从commons-loggging.properties配置文件中查找配置org.apache.commons.logging.LogFactory配置，如果没找到，则进入下一步，否则直接到最后一步。<br>　　5. 采用默认的实现org.apache.commons.logging.impl.LogFactoryImpl，到最后一步。<br>　　6. 初始化完成后，放入第一步提到的Hashtable中缓存，最后返回。</p>
<h2 id="u6269_u5C55"><a href="#u6269_u5C55" class="headerlink" title="扩展"></a>扩展</h2><p>　　在commons-logging配置文件、或虚拟机属性中配置这个新的Logging框架的实现类（实现Log接口）</p>
<h2 id="u603B_u7ED3"><a href="#u603B_u7ED3" class="headerlink" title="总结"></a>总结</h2><p>　　通过上面的分析可以看出，commons-logging仅仅是一个日志框架的基石，提供了统一的使用接口。如果需要打印输出日志，则需要借助于log4j，jdk log等具体的实现，或者采用其自身提供的SimpleLog，向控制台打印输出。同时，也没有提供配置属性执行日志级别，好奇怪！源码下载地址为：<a href="/code/commons-logging-demo.rar">commons-logging-demo.rar</a></p>
<h2 id="u53C2_u8003_u8D44_u6599"><a href="#u53C2_u8003_u8D44_u6599" class="headerlink" title="参考资料"></a>参考资料</h2><p><a href="http://www.cnblogs.com/machine/archive/2012/12/17/2822227.html" target="_blank" rel="external">http://www.cnblogs.com/machine/archive/2012/12/17/2822227.html</a><br><a href="http://zhangjunhd.blog.51cto.com/113473/25135/" target="_blank" rel="external">http://zhangjunhd.blog.51cto.com/113473/25135/</a><br><a href="http://blog.csdn.net/gxmark/article/details/7338253" target="_blank" rel="external">http://blog.csdn.net/gxmark/article/details/7338253</a><br><a href="http://pangwu86.iteye.com/blog/1122082" target="_blank" rel="external">http://pangwu86.iteye.com/blog/1122082</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/15/log/1.日志系列之commons-logging/" data-id="cijzzpvch00bd1cfsbdw22evg" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/common-loggings/">common-loggings</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/log/">log</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-redis/6.Redis系列之发布-订阅模式" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/11/redis/6.Redis系列之发布-订阅模式/" class="article-date">
  <time datetime="2015-12-11T09:00:00.000Z" itemprop="datePublished">2015-12-11</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/redis/">redis</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/11/redis/6.Redis系列之发布-订阅模式/">Redis系列五之发布-订阅模式</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　redis支持发布订阅模式，但是其存在一个问题就是；<strong>如果订阅者宕机，在此期间发布者发布的数据都将丢失，即使订阅者重启后也收不到数据</strong></p>
<h2 id="u5B9E_u73B0"><a href="#u5B9E_u73B0" class="headerlink" title="实现"></a>实现</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> <span class="keyword">implements</span> <span class="title">Serializable</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span><br><span class="line"> * 发布者</span><br><span class="line"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestPub</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Jedis jedis = <span class="keyword">new</span> Jedis(<span class="string">"localhost"</span>, <span class="number">6379</span>);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            User bean = <span class="keyword">new</span> User();</span><br><span class="line">            bean.setName(<span class="string">"test"</span>);</span><br><span class="line">            <span class="comment">//使用ObjectOutputStream和ByteArrayOutputStream将对象转换成字节流</span></span><br><span class="line">            ByteArrayOutputStream baos = <span class="keyword">new</span> ByteArrayOutputStream();</span><br><span class="line">            ObjectOutputStream oos = <span class="keyword">new</span> ObjectOutputStream(baos);</span><br><span class="line">            oos.writeObject(bean);</span><br><span class="line">            String msg1 = baos.toString(<span class="string">"ISO-8859-1"</span>);<span class="comment">//指定字符集将字节流解码成字符串，否则在订阅时，转换会有问题。</span></span><br><span class="line">            <span class="comment">// msg1 = URLEncoder.encode(msg1, "UTF-8");</span></span><br><span class="line">            jedis.publish(<span class="string">"foo"</span>, msg1);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            System.out.println(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span><br><span class="line"> * 订阅者</span><br><span class="line"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestSub</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Jedis jedis = <span class="keyword">new</span> Jedis(<span class="string">"localhost"</span>, <span class="number">6379</span>);</span><br><span class="line">        JedisPubSub jedisPubSub = <span class="keyword">new</span> JedisPubSub() &#123;</span><br><span class="line">            <span class="annotation">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onUnsubscribe</span><span class="params">(String channel, <span class="keyword">int</span> subscribedChannels)</span> </span>&#123;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="annotation">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onSubscribe</span><span class="params">(String channel, <span class="keyword">int</span> subscribedChannels)</span> </span>&#123;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="annotation">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onPUnsubscribe</span><span class="params">(String pattern, <span class="keyword">int</span> subscribedChannels)</span> </span>&#123;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="annotation">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onPSubscribe</span><span class="params">(String pattern, <span class="keyword">int</span> subscribedChannels)</span> </span>&#123;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="annotation">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onPMessage</span><span class="params">(String pattern, String channel,</span><br><span class="line">                                   String message)</span> </span>&#123;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="annotation">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onMessage</span><span class="params">(String channel, String message)</span> </span>&#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    ByteArrayInputStream bis = <span class="keyword">new</span> ByteArrayInputStream(</span><br><span class="line">                            message.getBytes(<span class="string">"ISO-8859-1"</span>));<span class="comment">//此处指定字符集将字符串编码成字节数组，此处的字符集需要与发布时的字符集保持一致</span></span><br><span class="line">                    ObjectInputStream ois = <span class="keyword">new</span> ObjectInputStream(bis);</span><br><span class="line">                    User bean = (User) ois.readObject();</span><br><span class="line">                    System.out.println(bean.getName());</span><br><span class="line">                &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line"></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        jedis.subscribe(jedisPubSub, <span class="string">"foo"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>　　代码下载地址：<a href="/code/redis-pubsub.zip">redis-pubsub.zip</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/11/redis/6.Redis系列之发布-订阅模式/" data-id="cijzzpv5q003o1cfseicy4f32" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/redis/">redis</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-redis/5.Redis系列之配置文件" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/11/redis/5.Redis系列之配置文件/" class="article-date">
  <time datetime="2015-12-11T08:00:00.000Z" itemprop="datePublished">2015-12-11</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/redis/">redis</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/11/redis/5.Redis系列之配置文件/">Redis系列五之配置文件</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <ol>
<li>Redis默认不是以守护进程的方式运行，可以通过该配置项修改，使用yes启用守护进程<br> daemonize no</li>
<li>当Redis以守护进程方式运行时，Redis默认会把pid写入/var/run/redis.pid文件，可以通过pidfile指定<br> pidfile /var/run/redis.pid</li>
<li>指定Redis监听端口，默认端口为6379，作者在自己的一篇博文中解释了为什么选用6379作为默认端口，因为6379在手机按键上MERZ对应的号码，而MERZ取自意大利歌女Alessia Merz的名字<br> port 6379</li>
<li>绑定的主机地址，指定能监听哪些客户端的连接<br> bind 127.0.0.1<br>5.当 客户端闲置多长时间后关闭连接，如果指定为0，表示关闭该功能<br> timeout 300</li>
<li>指定日志记录级别，Redis总共支持四个级别：debug、verbose、notice、warning，默认为verbose<br> loglevel verbose</li>
<li>日志记录方式，默认为标准输出，如果配置Redis为守护进程方式运行，而这里又配置为日志记录方式为标准输出，则日志将会发送给/dev/null<br> logfile stdout</li>
<li>设置数据库的数量，默认数据库为0，可以使用SELECT <dbid>命令在连接上指定数据库id，通过redis-desktop-manager可以看到共新建了16个数据库<br> databases 16</dbid></li>
<li><p>指定在多长时间内，有多少次更新操作，就将数据同步到数据文件，可以多个条件配合<br> save <seconds> <changes><br> Redis默认配置文件中提供了三个条件：<br> save 900 1<br> save 300 10<br> save 60 10000<br> 分别表示900秒（15分钟）内有1个更改，300秒（5分钟）内有10个更改以及60秒内有10000个更改。</changes></seconds></p>
</li>
<li><p>指定存储至本地数据库时是否压缩数据，默认为yes，Redis采用LZF压缩，如果为了节省CPU时间，可以关闭该选项，但会导致数据库文件变的巨大<br>rdbcompression yes</p>
</li>
<li>指定本地数据库文件名，默认值为dump.rdb<br>dbfilename dump.rdb</li>
<li>指定本地数据库存放目录<br>dir ./</li>
<li>设置当本机为slave服务时，设置master服务的IP地址及端口，在Redis启动时，它会自动从master进行数据同步<br>slaveof <masterip> <masterport></masterport></masterip></li>
<li>当master服务设置了密码保护时，slave服务连接master的密码<br>masterauth <master-password></master-password></li>
<li>设置Redis连接密码，如果配置了连接密码，客户端在连接Redis时需要通过AUTH <password>命令提供密码，默认关闭<br>requirepass foobared</password></li>
<li>设置同一时间最大客户端连接数，默认无限制，Redis可以同时打开的客户端连接数为Redis进程可以打开的最大文件描述符数，如果设置 maxclients 0，表示不作限制。当客户端连接数到达限制时，Redis会关闭新的连接并向客户端返回max number of clients reached错误信息<br>maxclients 128</li>
<li>指定Redis最大内存限制，Redis在启动时会把数据加载到内存中，达到最大内存后，Redis会先尝试清除已到期或即将到期的Key，当此方法处理 后，仍然到达最大内存设置，将无法再进行写入操作，但仍然可以进行读取操作。Redis新的vm机制，会把Key存放内存，Value会存放在swap区<br>maxmemory <bytes></bytes></li>
<li>指定是否在每次更新操作后进行日志记录（预写日志问题），Redis在默认情况下是异步的把数据写入磁盘，如果不开启，可能会在断电时导致一段时间内的数据丢失。因为 redis本身同步数据文件是按上面save条件来同步的，所以有的数据会在一段时间内只存在于内存中。默认为no<br>appendonly no</li>
<li>指定更新日志文件名，默认为appendonly.aof<br> appendfilename appendonly.aof</li>
<li><p>指定更新日志条件，共有3个可选值：<br>no：表示等操作系统进行数据缓存同步到磁盘（快）<br>always：表示每次更新操作后手动调用fsync()将数据写到磁盘（慢，安全）<br>everysec：表示每秒同步一次（折衷，默认值）<br>appendfsync everysec</p>
</li>
<li><p>指定是否启用虚拟内存机制，默认值为no，简单的介绍一下，VM机制将数据分页存放，由Redis将访问量较少的页即冷数据swap到磁盘上，访问多的页面由磁盘自动换出到内存中（在后面的文章我会仔细分析Redis的VM机制）<br> vm-enabled no</p>
</li>
<li>虚拟内存文件路径，默认值为/tmp/redis.swap，不可多个Redis实例共享<br> vm-swap-file /tmp/redis.swap</li>
<li>将所有大于vm-max-memory的数据存入虚拟内存,无论vm-max-memory设置多小,所有索引数据都是内存存储的(Redis的索引数据 就是keys),也就是说,当vm-max-memory设置为0的时候,其实是所有value都存在于磁盘。默认值为0<br> vm-max-memory 0</li>
<li>Redis swap文件分成了很多的page，一个对象可以保存在多个page上面，但一个page上不能被多个对象共享，vm-page-size是要根据存储的 数据大小来设定的，作者建议如果存储很多小对象，page大小最好设置为32或者64bytes；如果存储很大大对象，则可以使用更大的page，如果不 确定，就使用默认值<br> vm-page-size 32</li>
<li>设置swap文件中的page数量，由于页表（一种表示页面空闲或使用的bitmap）是在放在内存中的，，在磁盘上每8个pages将消耗1byte的内存。<br> vm-pages 134217728</li>
<li>设置访问swap文件的线程数,最好不要超过机器的核数,如果设置为0,那么所有对swap文件的操作都是串行的，可能会造成比较长时间的延迟。默认值为4<br> vm-max-threads 4</li>
<li>设置在向客户端应答时，是否把较小的包合并为一个包发送，默认为开启<br>glueoutputbuf yes</li>
<li>指定在超过一定的数量或者最大的元素超过某一临界值时，采用一种特殊的哈希算法<br>hash-max-zipmap-entries 64<br>hash-max-zipmap-value 512</li>
<li>指定是否激活重置哈希，默认为开启（后面在介绍Redis的哈希算法时具体介绍）<br>activerehashing yes</li>
<li>指定包含其它的配置文件，可以在同一主机上多个Redis实例之间使用同一份配置文件，而同时各个实例又拥有自己的特定配置文件<br>include /path/to/local.conf</li>
</ol>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/11/redis/5.Redis系列之配置文件/" data-id="cijzzpv5t003t1cfsinxzjgqv" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/redis/">redis</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-redis/4.Redis系列之Master-Slave" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/11/redis/4.Redis系列之Master-Slave/" class="article-date">
  <time datetime="2015-12-11T07:00:00.000Z" itemprop="datePublished">2015-12-11</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/redis/">redis</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/11/redis/4.Redis系列之Master-Slave/">Redis系列四之持久化</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u6982_u8FF0"><a href="#u6982_u8FF0" class="headerlink" title="概述"></a>概述</h2><p>　　redis提供的主从复制功能，让多个slave server拥有和master server相同的数据库副本。该机制的主要特点包括：<br>　　1. master可以有多个slave<br>　　2. 除了多个slave连到相同的master外，slave也可以连接其他slave形成图状结构<br>　　3. 主从复制不会阻塞master。也就是说当一个或多个slave与master进行初次同步数据时，master可以继续处理client发来的请求。<br>　　4. slave在初次同步数据时则会阻塞不能处理client的请求。<br>　　5. 主从复制可以用来提高系统的可伸缩性，我们可以用多个slave 专门用于client的读请求，如sort操作可以使用slave来处理。也可以用来做简单的数据冗余<br>　　6. 可以在master禁用数据持久化，只需要注释掉master 配置文件中的所有save配置，然后只在slave上配置数据持久化</p>
<h2 id="u4E3B_u4ECE_u590D_u5236_u8FC7_u7A0B"><a href="#u4E3B_u4ECE_u590D_u5236_u8FC7_u7A0B" class="headerlink" title="主从复制过程"></a>主从复制过程</h2><p>　　1. 当设置好slave服务器后，slave会建立和master的连接，然后发送sync命令。<br>　　2. 无论是第一次同步建立的连接还是连接断开后的重新连接，master都会启动一个后台进程，将数据库快照保存到文件中。<br>　　3. 同时master主进程会开始收集新的写命令并缓存起来。后台进程完成写文件 后，master就发送文件给slave，slave将文件保存到磁盘上，<br>　　4. slave加载文件到内存，恢复数据库快照到slave上。接着master就会把缓存的命令转发给slave。<br>　　5. 后续master收到的写命令都会通过开始建立的连接发送给slave<br>　　6. 从master到slave的同步数据的命令和从 client发送的命令使用相同的协议格式。当master和slave的连接断开时slave可以自动重新建立连接。<br>　　7. 如果master同时收到多个 slave发来的同步连接命令，只会使用启动一个进程来写数据库镜像，然后发送给所有slave。</p>
<h2 id="u914D_u7F6E"><a href="#u914D_u7F6E" class="headerlink" title="配置"></a>配置</h2><p>　　配置slave服务器很简单，只需要在配置文件中加入如下配置：slaveof 192.168.1.1 6379  #指定master的ip和端口 </p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/11/redis/4.Redis系列之Master-Slave/" data-id="cijzzpv5w003w1cfsbocukun7" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/redis/">redis</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-redis/3.Redis系列之持久化" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/11/redis/3.Redis系列之持久化/" class="article-date">
  <time datetime="2015-12-11T06:00:00.000Z" itemprop="datePublished">2015-12-11</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/redis/">redis</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/11/redis/3.Redis系列之持久化/">Redis系列三之持久化</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u6982_u8FF0"><a href="#u6982_u8FF0" class="headerlink" title="概述"></a>概述</h2><p>　　在redis中，提供了两种方式的持久化机制，分别为：RDB、AOF<br>　　1. RDB(point-in-time snapshot)：按照指定的时间间隔生成数据集的时间点快照<br>　　2. AOF(append-only file)：redis服务器记录所有的写操作命令，并在服务器启动时，通过重新执行这些命令来还原数据集。AOF 文件中的命令全部以 Redis 协议的格式来保存，新命令会被追加到 AOF 文件的末尾。 Redis 还可以在后台对 AOF 文件进行重写（rewrite），使得 AOF 文件的体积不会超出保存数据集状态所需的实际大小。通过修改配置文件来打开 AOF 功能：appendonly yes<br>　　3. AOF 和 RDB 混合方式。在这种情况下，当 Redis 重启时， 它会优先使用 AOF 文件来还原数据集，因为 AOF 文件保存的数据集通常比 RDB 文件所保存的数据集更完整。<br>　　当然，我们也可以关闭持久化功能，使redis完全作为一个内存缓存服务器。</p>
<h2 id="RDB_u6267_u884C_u65B9_u5F0F"><a href="#RDB_u6267_u884C_u65B9_u5F0F" class="headerlink" title="RDB执行方式"></a>RDB执行方式</h2><p>　　1. Redis 调用 fork()，同时拥有父进程和子进程。<br>　　2. 子进程将数据集写入到一个临时 RDB 文件中，此时父进程无须执行任何磁盘 I/O 操作<br>　　3. 子进程完成对新 RDB 文件的写入后，Redis 用新 RDB 文件替换原来的 RDB 文件，并删除旧的 RDB 文件。</p>
<h2 id="AOF_u6267_u884C_u65B9_u5F0F"><a href="#AOF_u6267_u884C_u65B9_u5F0F" class="headerlink" title="AOF执行方式"></a>AOF执行方式</h2><p>　　每当 Redis 执行一个改变数据集的命令时（比如 SET），就将这个命令追加到 AOF 文件的末尾</p>
<h2 id="AOF_u91CD_u5199"><a href="#AOF_u91CD_u5199" class="headerlink" title="AOF重写"></a>AOF重写</h2><p>　　AOF的运作方式是不断地将命令追加到文件的末尾，所以随着写入命令的不断增加，AOF文件的体积也会变得越来越大。举个例子，如果你对一个计数器调用了 100 次 INCR ，AOF 文件就需要使用 100 条记录（entry）。然而在实际上， 只使用一条 SET 命令已经足以保存计数器的当前值了，其余 99 条记录实际上都是多余的。为了处理这种情况，Redis 提供了一个特性：在不打断服务客户端的情况下， 当 AOF 文件体积变得过大时，redis 将对 AOF 文件进行重建（rebuild）。执行 BGREWRITEAOF 命令， Redis 将生成一个新的 AOF 文件， 这个文件包含重建当前数据集所需的最少命令。<br>　　整个重写操作是绝对安全的，因为 Redis 在创建新 AOF 文件的过程中，会继续将命令追加到现有的 AOF 文件里面，即使重写过程中发生停机，现有的 AOF 文件也不会丢失。 而一旦新 AOF 文件创建完毕，Redis 就会从旧 AOF 文件切换到新 AOF 文件，并开始对新 AOF 文件进行追加操作。</p>
<h2 id="AOF_u91CD_u5199_u673A_u5236"><a href="#AOF_u91CD_u5199_u673A_u5236" class="headerlink" title="AOF重写机制"></a>AOF重写机制</h2><p>　　1. Redis 执行 fork() ，现在同时拥有父进程和子进程。<br>　　2. 子进程开始将新 AOF 文件的内容写入到临时文件。<br>　　3. 对于所有新执行的写入命令，父进程一边将它们累积到一个内存缓存中，一边将这些改动追加到现有 AOF 文件的末尾：这样即使在重写的中途发生停机，现有的 AOF 文件也还是安全的。<br>　　4. 当子进程完成重写工作时，它给父进程发送一个信号，父进程在接收到信号之后，将内存缓存中的所有数据追加到新 AOF 文件的末尾。<br>　　5. Redis 原子地用新文件替换旧文件，之后所有命令都会直接追加到新 AOF 文件的末尾。</p>
<h2 id="RDB_u4F18_u70B9"><a href="#RDB_u4F18_u70B9" class="headerlink" title="RDB优点"></a>RDB优点</h2><p>　　RDB 是一个非常紧凑（compact）的文件，它保存了 Redis 在某个时间点上的数据集， 这种文件非常适合用于进行备份，进行灾难恢复（disaster recovery）。RDB 在恢复大数据集时的速度比 AOF 的恢复速度要快。</p>
<h2 id="RDB_u7F3A_u70B9"><a href="#RDB_u7F3A_u70B9" class="headerlink" title="RDB缺点"></a>RDB缺点</h2><p>　　容易在服务器故障时丢失数据：在两次保存数据的时间端内数据发生变化，redis故障，发生了变化的数据会丢失<br>　　数据集比较庞大时，fork() 可能会非常耗时，造成服务器在N毫秒内停止处理客户端； 如果数据集非常巨大，并且 CPU 时间非常紧张的话，那么这种停止时间甚至可能会长达整整一秒。</p>
<h2 id="AOF_u4F18_u70B9"><a href="#AOF_u4F18_u70B9" class="headerlink" title="AOF优点"></a>AOF优点</h2><p>　　通过设置不同的 fsync 策略，比如无 fsync ，每秒钟一次 fsync ，或者每次执行写入命令时 fsync（频繁调用 fsync 注定了这种策略不可能快得起来。） 。 AOF 的默认策略为每秒钟 fsync 一次，在这种配置下，Redis 仍然可以保持良好的性能，并且就算发生故障停机，也最多只会丢失一秒钟的数据（ fsync 会在后台线程执行，所以主线程可以继续努力地处理命令请求）。<br>　　AOF 文件是一个只进行追加操作的日志文件（append only log）， 因此对 AOF 文件的写入不需要进行 seek ， 即使日志因为某些原因而包含了未写入完整的命令（比如写入时磁盘已满，写入中途停机，等等）， redis-check-aof 工具也可以轻易地修复这种问题。<br>　　AOF 文件有序地保存了对数据库执行的所有写入操作， 这些写入操作以 Redis 协议的格式保存， 因此 AOF 文件的内容非常容易被人读懂， 对文件进行分析（parse）也很轻松。 导出（export） AOF 文件也非常简单： 举个例子， 如果你不小心执行了 FLUSHALL 命令， 但只要 AOF 文件未被重写， 那么只要停止服务器， 移除 AOF 文件末尾的 FLUSHALL 命令， 并重启 Redis ， 就可以将数据集恢复到 FLUSHALL 执行之前的状态。</p>
<h2 id="AOF_u7F3A_u70B9"><a href="#AOF_u7F3A_u70B9" class="headerlink" title="AOF缺点"></a>AOF缺点</h2><p>　　对于相同的数据集来说，AOF 文件的体积通常要大于 RDB 文件的体积。<br>　　根据所使用的 fsync 策略，AOF 的速度可能会慢于 RDB 。 在一般情况下， 每秒 fsync 的性能依然非常高， 而关闭 fsync 可以让 AOF 的速度和 RDB 一样快， 即使在高负荷之下也是如此。 不过在处理巨大的写入载入时，RDB 可以提供更有保证的最大延迟时间（latency）。<br>　　AOF 在过去曾经发生过这样的 bug ： 因为个别命令的原因，导致 AOF 文件在重新载入时，无法将数据集恢复成保存时的原样。 （举个例子，阻塞命令 BRPOPLPUSH 就曾经引起过这样的 bug 。） 测试套件里为这种情况添加了测试： 它们会自动生成随机的、复杂的数据集， 并通过重新载入这些数据来确保一切正常。 虽然这种 bug 在 AOF 文件中并不常见， 但是对比来说， RDB 几乎是不可能出现这种 bug 的。</p>
<h2 id="AOF_u6587_u4EF6_u4FEE_u590D"><a href="#AOF_u6587_u4EF6_u4FEE_u590D" class="headerlink" title="AOF文件修复"></a>AOF文件修复</h2><p>　　服务器可能在程序正在对 AOF 文件进行写入时停机，如果停机造成了 AOF 文件出错（corrupt）， 那么 Redis 在重启时会拒绝载入这个 AOF 文件，从而确保数据的一致性不会被破坏。当发生这种情况时， 可以用以下方法来修复出错的 AOF 文件：</p>
<ol>
<li>为现有的 AOF 文件创建一个备份。</li>
<li><p>使用 Redis 附带的 redis-check-aof 程序，对原来的 AOF 文件进行修复。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ redis-check-aof --fix</span><br></pre></td></tr></table></figure>
</li>
<li><p>(可选)使用 diff -u 对比修复后的 AOF 文件和原始 AOF 文件的备份，查看两个文件之间的不同之处。</p>
</li>
<li>重启 Redis 服务器，等待服务器载入修复后的 AOF 文件，并进行数据恢复。</li>
</ol>
<h2 id="RDB_u5907_u4EFD_u8FC7_u7A0B"><a href="#RDB_u5907_u4EFD_u8FC7_u7A0B" class="headerlink" title="RDB备份过程"></a>RDB备份过程</h2><p>redis-cli&gt; CONFIG SET appendonly yes   #确保写命令会被正确地追加到 AOF 文件的末尾。（ Redis 会阻塞直到初始 AOF 文件创建完成为止， 之后 Redis 会继续处理命令请求， 并开始将写入命令追加到 AOF 文件末尾。）<br>redis-cli&gt; CONFIG SET save “”          #关闭 RDB 功能，确保命令执行之后，数据库的键的数量没有改变。</p>
<h2 id="u76F8_u4E92_u5F71_u54CD"><a href="#u76F8_u4E92_u5F71_u54CD" class="headerlink" title="相互影响"></a>相互影响</h2><p>　　在版本号大于等于 2.4 的 Redis 中， BGSAVE 执行的过程中，不可以执行 BGREWRITEAOF 。反过来说，在 BGREWRITEAOF 执行的过程中，也不可以执行 BGSAVE 。这可以防止两个 Redis 后台进程同时对磁盘进行大量的 I/O 操作。<br>　　如果 BGSAVE 正在执行，并且用户显示地调用 BGREWRITEAOF 命令， 那么服务器将向用户回复一个 OK 状态， 并告知用户， BGREWRITEAOF 已经被预定执行： 一旦 BGSAVE 执行完毕， BGREWRITEAOF 就会正式开始。当 Redis 启动时， 如果 RDB 持久化和 AOF 持久化都被打开了， 那么程序会优先使用 AOF 文件来恢复数据集， 因为 AOF 文件所保存的数据通常是最完整的。</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/11/redis/3.Redis系列之持久化/" data-id="cijzzpv60003z1cfsw20vel3b" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/redis/">redis</a></li></ul>

    </footer>
  </div>
  
</article>


  
  
    <nav id="page-nav">
      <a class="extend prev" rel="prev" href="/page/10/">&laquo; Prev</a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/9/">9</a><a class="page-number" href="/page/10/">10</a><span class="page-number current">11</span><a class="page-number" href="/page/12/">12</a><a class="page-number" href="/page/13/">13</a><span class="space">&hellip;</span><a class="page-number" href="/page/15/">15</a><a class="extend next" rel="next" href="/page/12/">Next &raquo;</a>
    </nav>
  
</section>
        
          <aside id="sidebar">
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Categories</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/cache/">cache</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/database/">database</a><span class="category-list-count">13</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/docker/">docker</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/gis/">gis</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/git/">git</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/go/">go</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/gradle/">gradle</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/groovy/">groovy</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/hadoop/">hadoop</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/java/">java</a><span class="category-list-count">18</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/linux/">linux</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/log/">log</a><span class="category-list-count">11</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/mongodb/">mongodb</a><span class="category-list-count">14</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/mq/">mq</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/mybatis/">mybatis</a><span class="category-list-count">9</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/netty/">netty</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/nginx/">nginx</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/nio/">nio</a><span class="category-list-count">19</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/nodejs/">nodejs</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/redis/">redis</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/rpc/">rpc</a><span class="category-list-count">14</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/spring/">spring</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/tomcat/">tomcat</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/zookeeper/">zookeeper</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/杂项/">杂项</a><span class="category-list-count">2</span></li></ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/aop/">aop</a><span class="tag-list-count">8</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/aspectj/">aspectj</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/cache/">cache</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/classloader/">classloader</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/common-loggings/">common-loggings</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/commonjs/">commonjs</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/database/">database</a><span class="tag-list-count">10</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/docker/">docker</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/dubbo/">dubbo</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/fastdfs/">fastdfs</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/gclib/">gclib</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/geohash/">geohash</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/gis/">gis</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/git/">git</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/go/">go</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/gradle/">gradle</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/groovy/">groovy</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/hadoop/">hadoop</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/hessisan/">hessisan</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/java/">java</a><span class="tag-list-count">48</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/javassist/">javassist</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/kafka/">kafka</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/linux/">linux</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/log/">log</a><span class="tag-list-count">11</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/log4j/">log4j</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/logback/">logback</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/map/">map</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/memecached/">memecached</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mina/">mina</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mongodb/">mongodb</a><span class="tag-list-count">14</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mq/">mq</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mqtt/">mqtt</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mybatis/">mybatis</a><span class="tag-list-count">9</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/netty/">netty</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nginx/">nginx</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nio/">nio</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nodejs/">nodejs</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/postgresql/">postgresql</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/protobuf/">protobuf</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/proxy/">proxy</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/push/">push</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/rabbitmq/">rabbitmq</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/redis/">redis</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/rpc/">rpc</a><span class="tag-list-count">14</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/sitemesh/">sitemesh</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/sld/">sld</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/slf4j/">slf4j</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/socket/">socket</a><span class="tag-list-count">7</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/spatialite-for-android/">spatialite for android</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/spi/">spi</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/spring/">spring</a><span class="tag-list-count">13</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/tomcat/">tomcat</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/transaction/">transaction</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/web/">web</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/xSocket/">xSocket</a><span class="tag-list-count">7</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/zbus/">zbus</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/zookeeper/">zookeeper</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/数据结构/">数据结构</a><span class="tag-list-count">2</span></li></ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/aop/" style="font-size: 15.38px;">aop</a> <a href="/tags/aspectj/" style="font-size: 11.54px;">aspectj</a> <a href="/tags/cache/" style="font-size: 11.54px;">cache</a> <a href="/tags/classloader/" style="font-size: 10px;">classloader</a> <a href="/tags/common-loggings/" style="font-size: 10px;">common-loggings</a> <a href="/tags/commonjs/" style="font-size: 12.31px;">commonjs</a> <a href="/tags/database/" style="font-size: 16.92px;">database</a> <a href="/tags/docker/" style="font-size: 13.85px;">docker</a> <a href="/tags/dubbo/" style="font-size: 10px;">dubbo</a> <a href="/tags/fastdfs/" style="font-size: 10px;">fastdfs</a> <a href="/tags/gclib/" style="font-size: 10.77px;">gclib</a> <a href="/tags/geohash/" style="font-size: 10px;">geohash</a> <a href="/tags/gis/" style="font-size: 10px;">gis</a> <a href="/tags/git/" style="font-size: 10.77px;">git</a> <a href="/tags/go/" style="font-size: 10px;">go</a> <a href="/tags/gradle/" style="font-size: 10px;">gradle</a> <a href="/tags/groovy/" style="font-size: 10px;">groovy</a> <a href="/tags/hadoop/" style="font-size: 10px;">hadoop</a> <a href="/tags/hessisan/" style="font-size: 11.54px;">hessisan</a> <a href="/tags/java/" style="font-size: 20px;">java</a> <a href="/tags/javassist/" style="font-size: 10px;">javassist</a> <a href="/tags/kafka/" style="font-size: 11.54px;">kafka</a> <a href="/tags/linux/" style="font-size: 12.31px;">linux</a> <a href="/tags/log/" style="font-size: 17.69px;">log</a> <a href="/tags/log4j/" style="font-size: 12.31px;">log4j</a> <a href="/tags/logback/" style="font-size: 13.08px;">logback</a> <a href="/tags/map/" style="font-size: 10px;">map</a> <a href="/tags/memecached/" style="font-size: 10.77px;">memecached</a> <a href="/tags/mina/" style="font-size: 13.08px;">mina</a> <a href="/tags/mongodb/" style="font-size: 19.23px;">mongodb</a> <a href="/tags/mq/" style="font-size: 13.85px;">mq</a> <a href="/tags/mqtt/" style="font-size: 10.77px;">mqtt</a> <a href="/tags/mybatis/" style="font-size: 16.15px;">mybatis</a> <a href="/tags/netty/" style="font-size: 10px;">netty</a> <a href="/tags/nginx/" style="font-size: 11.54px;">nginx</a> <a href="/tags/nio/" style="font-size: 13.08px;">nio</a> <a href="/tags/nodejs/" style="font-size: 10px;">nodejs</a> <a href="/tags/postgresql/" style="font-size: 10.77px;">postgresql</a> <a href="/tags/protobuf/" style="font-size: 10px;">protobuf</a> <a href="/tags/proxy/" style="font-size: 10px;">proxy</a> <a href="/tags/push/" style="font-size: 10px;">push</a> <a href="/tags/rabbitmq/" style="font-size: 11.54px;">rabbitmq</a> <a href="/tags/redis/" style="font-size: 13.85px;">redis</a> <a href="/tags/rpc/" style="font-size: 19.23px;">rpc</a> <a href="/tags/sitemesh/" style="font-size: 10px;">sitemesh</a> <a href="/tags/sld/" style="font-size: 10px;">sld</a> <a href="/tags/slf4j/" style="font-size: 10px;">slf4j</a> <a href="/tags/socket/" style="font-size: 14.62px;">socket</a> <a href="/tags/spatialite-for-android/" style="font-size: 10px;">spatialite for android</a> <a href="/tags/spi/" style="font-size: 10px;">spi</a> <a href="/tags/spring/" style="font-size: 18.46px;">spring</a> <a href="/tags/tomcat/" style="font-size: 10.77px;">tomcat</a> <a href="/tags/transaction/" style="font-size: 10px;">transaction</a> <a href="/tags/web/" style="font-size: 10px;">web</a> <a href="/tags/xSocket/" style="font-size: 14.62px;">xSocket</a> <a href="/tags/zbus/" style="font-size: 10px;">zbus</a> <a href="/tags/zookeeper/" style="font-size: 10.77px;">zookeeper</a> <a href="/tags/数据结构/" style="font-size: 10.77px;">数据结构</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/01/">January 2016</a><span class="archive-list-count">67</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/12/">December 2015</a><span class="archive-list-count">81</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/11/">November 2015</a><span class="archive-list-count">2</span></li></ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recents</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2016/01/30/资料/">(no title)</a>
          </li>
        
          <li>
            <a href="/2016/01/30/java/13.Classloader系列一/">ClassLoader系列一</a>
          </li>
        
          <li>
            <a href="/2016/01/29/hadoop/1.hadoop系列之源码编译/">hadoop系列一之源码编译</a>
          </li>
        
          <li>
            <a href="/2016/01/29/go/1.GO系列之入门/">Go系列一之入门</a>
          </li>
        
          <li>
            <a href="/2016/01/28/tomcat/2.tomcat性能优化/">tomcat性能优化</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2016 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="http://libs.baidu.com/jquery/2.0.3/jquery.min.js"></script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css" type="text/css">
  <script src="/fancybox/jquery.fancybox.pack.js" type="text/javascript"></script>


<script src="/js/script.js" type="text/javascript"></script>

  </div>
</body>
</html>